import QtQuick 2.0
import QtQuick.Controls 1.2
import "../../javascript/Utils.js" as UtilsJS

import Utils 1.0

IOSWebView {
    id: map
    url: "http://127.0.0.1:8081/MAPA"

    property var mapaContent: null
    property bool initialized: false
    property var toAdd: new Array()

    property var center: {"latitude": "0", "longitude": "0"}

    signal markerClicked(string id, string label)

    WebviewUtils {
        id: wvUtils
        onRequestReceived: {
            console.log("REQUEST: "+req);

            var index = req.indexOf(":");
            var key = req.substring(0,index);
            var val = req.substring(index+1);
            if(key=="markerClicked") {
                index = val.indexOf(",");
                var id = val.substring(0,index);
                var nome = val.substring(index+1);
                applicationWindow.exibeProdutos(id,nome);
            } else if(key=="newPos") {
                applicationWindow.setCurrentPos(val);
                if(!initialized) {
                    initialized = true;
                    var i;
                    for(i=0; i<toAdd.length; i++) {
                        addMarker(toAdd[i]["id"],toAdd[i]["lat"],toAdd[i]["lon"],
                        toAdd[i]["color"],toAdd[i]["nome"]);
                    }
                }
            }
        }
    }

    function deleteMarkers() {
        wvUtils.clearPins();
        map.url = ""
        map.url = "http://127.0.0.1:8081/MAPA"
    }

    function addMarker(id, lat , lon, label, color) {
        wvUtils.addPin(id,lat,lon,label,color);
    }

    function addMarkers(estabelecimentos) {
        var i;
        for(i=0; i<estabelecimentos.length; i++) {
            var cor = "#000000";
            if(estabelecimentos[i]["color"]=="red") cor = "#FF0000";
            if(estabelecimentos[i]["color"]=="green") cor = "#00FF00";
            if(estabelecimentos[i]["color"]=="yellow") cor = "#FFFF00";
            if(estabelecimentos[i]["color"]=="blue") cor = "#0000FF";
            addMarker(estabelecimentos[i]["id"],estabelecimentos[i]["lat"],estabelecimentos[i]["lon"],
                      estabelecimentos[i]["nome"],cor);
        }
        map.url = ""
        map.url = "http://127.0.0.1:8081/MAPA"
    }

    function setCenter(lat, lon) {
//        map.center.latitude = lat;
//        map.center.longitude = lon;
    }
}
